extends Node2D
class_name WorldWrap

# 地图边界配置
@export var map_width: float = 3000.0  # 地图宽度
@export var map_height: float = 3000.0  # 地图高度
@export var buffer_zone: float = 50.0   # 过渡缓冲区大小，避免立即传送回来

# 追踪需要循环的节点
var tracked_nodes: Array = []
var player_node = null

func _ready():
	# 获取玩家节点
	player_node = get_node("../World/Player")
	if player_node:
		tracked_nodes.append(player_node)
	
	# 等待一帧确保敌人可能已经生成
	await get_tree().process_frame
	
	# 添加现有的敌人到追踪列表
	register_existing_enemies()
	
	# 连接敌人管理器的信号，以便在新敌人生成时追踪它们
	var enemy_manager = get_node("../World/EnemyManager")
	if enemy_manager and enemy_manager.has_signal("enemy_spawned"):
		enemy_manager.connect("enemy_spawned", register_enemy)

# 将所有现有敌人添加到追踪列表
func register_existing_enemies():
	var enemies = get_tree().get_nodes_in_group("enemy_hitbox")
	for enemy_hitbox in enemies:
		var enemy = enemy_hitbox.get_parent()
		if enemy is BaseEnemy:
			tracked_nodes.append(enemy)

# 注册新生成的敌人
func register_enemy(enemy):
	if enemy and !tracked_nodes.has(enemy):
		tracked_nodes.append(enemy)

# 注销被销毁的敌人
func unregister_enemy(enemy):
	tracked_nodes.erase(enemy)

# 在物理处理过程中检查并处理循环
func _physics_process(_delta):
	for node in tracked_nodes:
		if is_instance_valid(node):
			wrap_node(node)
		else:
			# 如果节点不再有效，从追踪列表中移除
			tracked_nodes.erase(node)

# 实现节点的位置循环
func wrap_node(node: Node2D):
	var position = node.global_position
	var wrapped = false
	
	# 检查X轴越界
	if position.x < -buffer_zone:
		position.x += map_width
		wrapped = true
	elif position.x > map_width + buffer_zone:
		position.x -= map_width
		wrapped = true
		
	# 检查Y轴越界
	if position.y < -buffer_zone:
		position.y += map_height
		wrapped = true
	elif position.y > map_height + buffer_zone:
		position.y -= map_height
		wrapped = true
	
	# 如果位置发生变化，更新节点的全局位置
	if wrapped:
		node.global_position = position

# 添加敌人或其他实体到追踪列表
func add_tracked_node(node: Node2D):
	if node and !tracked_nodes.has(node):
		tracked_nodes.append(node)

# 从追踪列表中移除节点
func remove_tracked_node(node: Node2D):
	tracked_nodes.erase(node) 